package com.XDApp.xdbase.fragment;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.XDApp.xdbase.GloableParams;
import com.XDApp.xdbase.XDHttpClient;
import com.XDApp.xdbase.activitys.FreeWalkerAndToursActivity;
import com.XDApp.xdbase.activitys.SpecialActivity;
import com.XDApp.xdbase.activitys.TicketActivity;
import com.XDApp.xdbase.bean.SeneryEntity;
import com.XDApp.xdbase.utils.CommonUtil;
import com.XDApp.xdbase.utils.xdConfig;
import com.XDApp.xdbase.view.CRToast;
import com.XDApp.xdbase.xinsilu.R;
import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 首页
 * 
 * @author Administrator
 * 
 */
public class HomeFragment extends XDBaseFragment implements OnClickListener {
	private final int DELAYTIME = 5000;
	private static final String TAG = "HomeFragment";
	private ViewPager viewPager;
	private LinearLayout llPoints;
	private final int previousSelectPosition = 0;
	private TextView free_walker;// 自由行
	private TextView ticket;// 门票
	private TextView circus;// 周边
	private TextView tours;// 参团游
	private TextView special;// 特产商城
	private String[] listUrl;
	/** 进度条布局 */
	private View[] mPlanViews = new View[3];

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
			sendEmptyMessageDelayed(0, DELAYTIME);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View inflate = inflater.inflate(R.layout.fragment_home, container, false);
		viewPager = (ViewPager) inflate.findViewById(R.id.vPager);
		llPoints = (LinearLayout) inflate.findViewById(R.id.ll_points);
		free_walker = (TextView) inflate.findViewById(R.id.tv_freewalker);
		ticket = (TextView) inflate.findViewById(R.id.tv_ticket);
		circus = (TextView) inflate.findViewById(R.id.tv_circum);
		tours = (TextView) inflate.findViewById(R.id.tv_tours);
		special = (TextView) inflate.findViewById(R.id.tv_special);
		free_walker.setOnClickListener(this);
		ticket.setOnClickListener(this);
		circus.setOnClickListener(this);
		tours.setOnClickListener(this);
		special.setOnClickListener(this);
		getData();
		return inflate;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_freewalker:// 自由行
			Intent intent1 = new Intent(mContext, FreeWalkerAndToursActivity.class);
			intent1.putExtra("flag", "0");
			startActivity(intent1);
			break;
		case R.id.tv_ticket:// 门票
			Intent intent2 = new Intent(mContext, TicketActivity.class);
			startActivity(intent2);
			break;
		case R.id.tv_circum:// 周边
//			Intent intent3 = new Intent(mContext, CircumActivity.class);
//			startActivity(intent3);
			CRToast.show(mContext, "该版面暂缓开放");
			break;
		case R.id.tv_tours:// 参团游
			Intent intent4 = new Intent(mContext, FreeWalkerAndToursActivity.class);
			intent4.putExtra("flag", "1");
			startActivity(intent4);
			break;
		case R.id.tv_special:// 特产商城
			Intent intent5 = new Intent(mContext, SpecialActivity.class);
			startActivity(intent5);
			break;
		default:
			break;
		}
	}

	class ViewPagerAdapter extends PagerAdapter {
		private final String[] str;

		private ViewPagerAdapter(String[] str) {
			this.str = str;
		}

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		/**
		 * 判断出去的view是否等于进来的view 如果为true直接复用
		 */
		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		/**
		 * 销毁预加载以外的view对象, 会把需要销毁的对象的索引位置传进来就是position
		 */
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		/**
		 * 创建一个view
		 */
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			ImageView iv = new ImageView(mContext);
			iv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT,
					android.view.ViewGroup.LayoutParams.FILL_PARENT));
			iv.setScaleType(ScaleType.FIT_XY);
			ImageLoader.getInstance().displayImage(str[position % str.length], iv);
			container.addView(iv);
			return iv;
		}
	}

	// TODO 访问网络获取数据
	private void getData() {
		if (CommonUtil.checkNetState(mContext)) {
			RequestParams params = new RequestParams();

			XDHttpClient.post(xdConfig.HOME, params, new AsyncHttpResponseHandler() {
				private String data;

				@Override
				public void onSuccess(int statusCode, String content) {
					Log.e(TAG, content);
					// if (null != ProgressDialog && ProgressDialog.isShowing())
					// ProgressDialog.dismiss();
					if (content.startsWith("{")) {
						return;
					}
					try {
						JSONObject obj = new JSONObject(content);
						data = obj.getString("data");
					} catch (JSONException e) {
						e.printStackTrace();
					}

					if (TextUtils.isEmpty(data)) {
						CommonUtil.showToast(mContext, "获取数据失败");
						return;
					}

					SeneryEntity entity = JSON.parseObject(data, SeneryEntity.class);

					String str1 = null;
					try {
						str1 = new org.json.JSONObject(entity.getSeneryList()).getString("seneryUrl");
					} catch (JSONException e) {
						e.printStackTrace();
					}
					if (TextUtils.isEmpty(str1))
						return;
					listUrl = JSON.parseObject(str1, String[].class);
					mPlanViews = new View[listUrl.length];
					ViewPagerAdapter adapter = new ViewPagerAdapter(listUrl);
					viewPager.setAdapter(adapter);
					handler.sendEmptyMessageDelayed(0, DELAYTIME);
					for (int i = 0; i < listUrl.length; i++) {
						View view = View.inflate(mContext, R.layout.item_plan, null);
						mPlanViews[i] = view;
						llPoints.addView(view);
					}
					viewPager.setOnPageChangeListener(mOnPageChangeListener);
					llPoints.getChildAt(previousSelectPosition).setEnabled(true);
					setPagerSelected(0);
				}

				@Override
				public void onFailure(Throwable arg0, String arg1) {
					Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
				}
			});
		} else {
			Toast.makeText(mContext, R.string.pLease_check_network, 0).show();
		}
	}

	private void setPagerSelected(int position) {
		for (int i = 0; i < mPlanViews.length; i++) {
			if (position == i) {
				mPlanViews[i].setSelected(true);
			} else {
				mPlanViews[i].setSelected(false);
			}
		}
	}

	private final OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int position) {
			setPagerSelected(position % listUrl.length);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	};

	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		GloableParams.IMGCACHE.clear();
		super.onDestroy();
	}

}
